// packageLive/pages/video/list/list.js
var util = require('../../../../utils/util')   //引入配置公共请求接口
import { couponApi, video, getParamByScene, getAddrCode } from '../../../../config/config'
const app = getApp()
let leftHeight = 0, rightHeight = 0; //分别定义左右两边的高度
let query;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUrl: getApp().globalData.imgUrl,
    videoUrl: getApp().globalData.videoUrl,
    fixedMenu:false,// 是否固顶分类
    titleHead:0,
    menuHeight:0,
    menuTop:0,
    statusBarHeight: app.globalData.statusHeight,
    typeId: '',
    typeData:[],
    videoData: [],
    leftList: [],
    rightList: [],
    columnByData: {},
    classifyShow: false,
    columnId: '',
    columnName: '',
    /**-合伙人--*/
    isShowPartnerAll: 1,
    showPartnerCodePop: false,
    authorizationPopup: false,
    fullScreen: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('options', options)
    this.getTopHeight()
    app.getLogin((re)=>{
      if(!re){
        this.setData({
          authorizationPopup: true
        })
      }
    })
    let that = this
    if (!wx.getStorageSync('loginMsg').token) {
      app.initLogin() //初始化登录
    }
    // let addrCode = wx.getStorageSync('addrCode')
    //有合伙人信息，则分享进入(会话或扫码)
    if (options.scene || options.hid) {
      var scene = options.hid ? options.hid : decodeURIComponent(options.scene) //参数二维码传递过来的参数
      //会话进入
      if (options.hid) {
        var stInFun = setInterval(() => {
          if (wx.getStorageSync('getLocation') === 'N') {
            that.setData({
              showSetting: true
            })
          }
          if (wx.getStorageSync('loginMsg').token && wx.getStorageSync('addrCode').provinceCode) {
            that.setData({
              showSetting: false
            })
            clearInterval(stInFun)
            if (!wx.getStorageSync('loginMsg').loginState) {
              if (wx.getUserProfile) {
                app.getUserProfile(function(){
                  that.setData({
                    getPhoneNumberData:{
                      isShowGetPhoneNumber:true
                    }
                  })
                })
              } else {
                if(!wx.getStorageSync('loginMsg').bindingPhone){
                  that.setData({
                    getPhoneNumberData:{
                      isShowGetPhoneNumber:true
                    }
                  })
                }
              }
            }
            app.bindingPartner(options.hid)
            that.setData({
              columnId: options.id
            })
            that.getCategory(options.id)
            that.getColumnBy(options.id)
            // that.getmmsActivityPageUrl(options.id, wx.getStorageSync('addrCode').provinceCode)
          }
        }, 1000)
      } else {
        //二维码进入
        app.getShareCode(scene, (res) => {
          console.log('res', res)
          var stInFun = setInterval(() => {
            if (wx.getStorageSync('getLocation') === 'N') {
              that.setData({
                showSetting: true
              })
            }
            if (wx.getStorageSync('loginMsg').token && wx.getStorageSync('addrCode').provinceCode) {
              that.setData({
                showSetting: false
              })
              clearInterval(stInFun)
              if (!wx.getStorageSync('loginMsg').loginState) {
                if (wx.getUserProfile) {
                  app.getUserProfile(function(){
                    that.setData({
                      getPhoneNumberData:{
                        isShowGetPhoneNumber:true
                      }
                    })
                  })
                } else {
                  if(!wx.getStorageSync('loginMsg').bindingPhone){
                    that.setData({
                      getPhoneNumberData:{
                        isShowGetPhoneNumber:true
                      }
                    })
                  }
                }
              }
              app.bindingPartner(res.userId)
            }else{
              if (wx.getUserProfile) {
                app.getUserProfile(function(){
                  that.setData({
                    getPhoneNumberData:{
                      isShowGetPhoneNumber:true
                    }
                  })
                })
              } else {
                if(!wx.getStorageSync('loginMsg').bindingPhone){
                  that.setData({
                    getPhoneNumberData:{
                      isShowGetPhoneNumber:true
                    }
                  })
                }
              }
            }
            console.log('合伙人分享')
            console.log('扫码')
            app.reqFun.requestJson("GET", getParamByScene + options.scene, '', (response) => {
              if (response.data) {
                const res = response.data
                if (res.success == 1 && res.data && res.data.id) {
                  that.getCategory(res.data.id)
                  that.getColumnBy(res.data.id)
                  // that.getmmsActivityPageUrl(res.data.id, wx.getStorageSync('addrCode').provinceCode)
                  that.setData({
                    columnId: res.data.id
                  })
                  that.getUserLocation((res) => {
                    if (res.getSetting) {
                      that.setData({
                        showSetting: true
                      })
                    }
                  })
                }
              }
            })
          }, 1000)
        })
      }
    } else if (options.id) {
      // that.getmmsActivityPageUrl(options.id, addrCode.provinceCode)
      that.getCategory(options.id)
      that.getColumnBy(options.id)
      that.setData({
        columnId: options.id
      })
    } else {
      console.log('没有获取参数')
    }
  },
  getTopHeight(){
    const query = wx.createSelectorQuery()
    query.select('#collHead').boundingClientRect()
    query.exec((res)=>{
      this.setData({
        titleHead:res[0].height || 0
      })
    })
    const menu = wx.createSelectorQuery()
    menu.select('#menuHead').boundingClientRect()
    menu.exec((res)=>{
      this.setData({
        menuHeight:res[0].height || 0,
        menuTop:res[0].top || 0
      })
    })
    console.log('menuTop', this.data.menuTop)
  },
 // 监听滚动，固顶分类
 onPageScroll: function (e) {
  if (this.data.columnByData) {
    if(e.scrollTop>=224-this.data.titleHead){
      if(!this.data.fixedMenu){
        this.setData({
          fixedMenu:true
        })
      }
    }else{
      if(this.data.fixedMenu){
        this.setData({
          fixedMenu:false
        })
      }
    }
  } else {
    if(e.scrollTop>=this.data.menuTop-this.data.titleHead){
      if(!this.data.fixedMenu){
        this.setData({
          fixedMenu:true
        })
      }
    }else{
      if(this.data.fixedMenu){
        this.setData({
          fixedMenu:false
        })
      }
    }
  }
},
goreBack() { //返回
  wx.navigateBack({
    delta: 1
  })
},
  // 获取专栏信息
  getColumnBy(id){
    let url = video.getColumnByIdUrl+id
    app.reqFun.requestJson('POST', url, '', (res) => {
      if (res.data.success == 1) {
        this.setData({
          columnByData: res.data.data.videoIndexDTO,
          columnName: res.data.data.columnName
        })
      }
    }, true)
  },
  // 获取分类数据
  getCategory(id) {
    let url = video.getCategoryUrl+id
    app.reqFun.requestJson('POST', url, '', (res) => {
      if (res.data.success == 1) {
        let typeData = res.data.data
        let type = {
          id: '',
          categoryName: '全部'
        }
        typeData.unshift(type)
        this.setData({
          typeData: typeData,
          typeId: res.data.data[0].id
        })
        this.getVideoData(res.data.data[0].id)
      }
    }, true)
  },
   // 获取视频数据
   getVideoData(categoryId) {
    this.setData({
      videoData: [],
      leftList: [],
      rightList: [],
    })
    const userId = wx.getStorageSync('loginMsg').userId
    const pricePstCode =  wx.getStorageSync('addrCode').pricePstCode
    let url = ''
    if (categoryId) {
      url = video.getVideoUrl+'?pricePstCode='+pricePstCode+'&categoryId='+categoryId+'&columnId='+this.data.columnId+'&userId='+userId
      // url = video.getVideoUrl+'?categoryId='+categoryId+'&columnId='+this.data.columnId+'&userId='+userId
    } else {
      url = video.getVideoUrl+'?pricePstCode='+pricePstCode+'&columnId='+this.data.columnId+'&userId='+userId
      // url = video.getVideoUrl+'?columnId='+this.data.columnId+'&userId='+userId
    }
    app.reqFun.requestJson('POST', url, '', (res) => {
      if (res.data.success == 1) {
        let data = res.data.data
        for (var i = 0, l = data.length; i < l; i++) {
          data[i].PlayTyle = false
          data[i].PauseTyle = true
          if (data[i].titlePic.split('/')[0] === 'marketing') {
            data[i].titlePic = this.data.videoUrl + data[i].titlePic
          } else {
            data[i].titlePic = this.data.imgUrl + data[i].titlePic
          }
        }
        this.setData({
          videoData: data
        })
        this.isLeft()
      }
    }, true)
  },
  async isLeft() {
    const { videoData, leftList, rightList } = this.data;
    query = wx.createSelectorQuery();
    for (let [index, val] of videoData.entries()) {
      index % 2 === 0 ? leftList.push(val) : rightList.push(val); //判断两边高度，来觉得添加到那边
    }
    this.setData({
      leftList: leftList,
      rightList: rightList
    })
    // for (const item of videoData) {
    //  leftHeight <= rightHeight ? leftList.push(item) : rightList.push(item); //判断两边高度，来觉得添加到那边
    //  await this.getBoxHeight(leftList, rightList);
    // }
   },
   getBoxHeight(leftList, rightList) { //获取左右两边高度
    return new Promise((resolve, reject) => {
     this.setData({ leftList, rightList }, () => {
      const query = wx.createSelectorQuery().in(this)
      query.select('#left').boundingClientRect();
      query.select('#right').boundingClientRect();
      query.exec((res) => {
       leftHeight = res[0].height; //获取左边列表的高度
       rightHeight = res[1].height; //获取右边列表的高度
       resolve();
      });
     });
    })
   },
  // 切换优惠券类型
  tapTypeSelect(e) {
    this.setData({
      typeId: e.currentTarget.dataset.id,
      classifyShow: false
    })
    this.getVideoData(e.currentTarget.dataset.id)
  },
  classifyShowBtn() {
    this.setData({
      classifyShow: this.data.classifyShow?false:true
    })
  },
  goGoodsInfo(e) {
    let videoId = e.currentTarget.dataset.data.id
    let name = e.currentTarget.dataset.data.name
    let columnId = this.data.columnId
    wx.navigateTo({
      url: '/packageLive/pages/video/detail/video-swiper/video-swiper?id=' + videoId + '&name='+ name + '&columnId=' + columnId
    })
  },
  goPlayVideo(e) { //开始播放视频
    var that = this
    var item = e.currentTarget.dataset.item
    var videoplay = wx.createVideoContext('video' + item.id, this)
    // wx.getNetworkType({ // 获取网络类型
    //   success: function (res) {
    //     if (res.networkType != 'wifi') {
    //       that.setData({
    //         showNotWifiPaly: true
    //       })
    //       setTimeout(function () {
    //         that.setData({
    //           showNotWifiPaly: false
    //         })
    //       }, 1500)
    //     }
    //   }
    // })
    videoplay.play()
    let data = that.data.videoData
    for (var i = 0, l = data.length; i < l; i++) {
      if (data[i].id === item.id) {
        data[i].PlayTyle = true
        data[i].PauseTyle = false
      }
    }
    that.setData({
      videoData: data
    })
  },
  goPauseVideo(e) {
    var that = this
    var item = e.currentTarget.dataset.item
    var videopause = wx.createVideoContext('video' + item.id, this)
    videopause.pause()
    let data = that.data.videoData
    for (var i = 0, l = data.length; i < l; i++) {
      if (data[i].id === item.id) {
        data[i].PlayTyle = false
        data[i].PauseTyle = true
      }
    }
    that.setData({
      videoData: data
    })
  },
  palyEndLitten(e) {
    var that = this
    var item = e.currentTarget.dataset.item
    let data = that.data.videoData
    for (var i = 0, l = data.length; i < l; i++) {
      if (data[i].id === item.id) {
        data[i].PlayTyle = false
        data[i].PauseTyle = true
      }
    }
    that.setData({
      videoData: data
    })
  },
  bindfullscreenchange(e) {
    let fullScreen = e.detail.fullScreen //值true为进入全屏，false为退出全屏
    if (!fullScreen) { //退出全屏
      console.log('退出全屏')
      this.setData({
        fullScreen: false
      })
    } else { //进入全屏
      console.log('进入全屏')
      this.setData({
        fullScreen: true
      })
    }
  },
  pageJump(item) {
    console.log('点到没有')
    let linkType = item.currentTarget.dataset.item.linkType
    let linkAppId =  item.currentTarget.dataset.item.linkAppId
    let linkUrl = item.currentTarget.dataset.item.linkUrl
    console.log('linkUrl', linkUrl)
    if (linkType == 'otherMiniProgram') { // 其他小程序跳转
      this.goMeita(linkAppId)
    } else if (linkType == 'miniPage') {
      wx.navigateTo({
        url: linkUrl
      })
    } else if(linkType == 'h5' && linkUrl!== '/packagBuy/pages/found/crmweb/index') {
      wx.navigateTo({
        url: '/packagBuy/pages/marketing/poster/posterh5/posterh5?h5Url=' + linkUrl
      })
    } else if(linkUrl == '/packagBuy/pages/found/crmweb/index') {
      wx.navigateTo({
        url: '/packagBuy/pages/found/crmweb/index'
      })
    }
  },
   // 美搭小程序跳转
   goMeita(linkAppId) {
    wx.navigateToMiniProgram({
      appId: linkAppId,//小程序appid
      path: '',//跳转关联小程序app.json配置里面的地址
      extraData: {
        foo: 'bar'
      },
    //**重点**要打开的小程序版本，有效值 develop（开发版），trial（体验版），release（正式版）
      envVersion: 'release',
      success(res) {
        // 打开成功
      }
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: this.data.columnByData.columnName,
      desc: '视频专栏',
      path: `/packageLive/pages/video/list/list?id=${this.data.columnId}&hid=${wx.getStorageSync('loginMsg').userId}`
    }
  },
  //展开合伙人信息
  showPartnerAll: function () {
    let isShowPartnerAll;
    if (this.data.isShowPartnerAll == 1) {
      isShowPartnerAll = 0;
    } else {
      isShowPartnerAll = 1;
    }
    this.setData({
      isShowPartnerAll: isShowPartnerAll,
    })
  },
  //展示合伙人二维码
  partnerCode: function (e) {
    // this.setData({
    //   showPartnerCodePop: true,
    // })
    let codeImg=e.target.dataset.url
    wx.previewImage({
      urls:[codeImg],
      current: codeImg, // 当前显示图片的http链接
     })
  },
  //关闭合伙人二维码
  closeCodePop: function () {
    console.log("3253456678dsgudkdkgfksfvkjdsvbjkdsvbvkj")
    this.setData({
      showPartnerCodePop: false,
    })
  },
  //拨打合伙人电话
  partnerPhone: function () {
    let that = this;
    wx.makePhoneCall({
      phoneNumber: that.data.partnerInfo.partnerPhone,
    })
  },
    //获取用户地理位置
    getUserLocation: function (callback) {
      let that = this
      console.log('活动页定位')
      if (wx.getStorageSync('getLocation')) {
        console.log('首页等待appJs定位完成')
        var setGetLocation=setInterval(()=> {
          if (!wx.getStorageSync('getLocation')) {
            callback({
              'showSetting':true,
              'getSetting':true
            })
            clearInterval(setGetLocation)
          }
          if (wx.getStorageSync('locationInfo')) {
            let res = wx.getStorageSync('locationInfo')
            const latitude = res.latitude
            const longitude = res.longitude
            var laorln = util.qqMapTransBMap(latitude, longitude)
            wx.setStorageSync('latAndLong', laorln)
            var parms = {
              latitude: laorln.latitude,
              longitude: laorln.longitude
            }
            app.reqFun.requestJson('get', getAddrCode, parms, (res) => {
              if (res.data.success == 1) {
                // wx.setStorageSync('addrCode', res.data.data)
                let pricePstCode = res.data.data.pricePstCode
                // let cityCode = res.data.data.cityCode
                // that.getmmsActivityPageUrl(that.data.activityId, pricePstCode)
                // that.setData({
                //   thisAddress: res.data.data.city
                // })
              }
            })
            clearInterval(setGetLocation)
          }
        },1000)
        return
      }
      wx.getSetting({
        success(res) {
          if (res.authSetting['scope.userLocation'] != false) {
            wx.getLocation({
              type: 'wgs84',
              success(res) {
                const latitude = res.latitude
                const longitude = res.longitude
                var laorln = util.qqMapTransBMap(latitude, longitude)
                wx.setStorageSync('latAndLong', laorln)
                var parms = {
                  latitude: laorln.latitude,
                  longitude: laorln.longitude
                }
                app.reqFun.requestJson('get', getAddrCode, parms, (res) => {
                  if (res.data.success == 1) {
                    // wx.setStorageSync('addrCode', res.data.data)
                    let pricePstCode = res.data.data.pricePstCode
                    // let cityCode = res.data.data.cityCode
                    // that.getmmsActivityPageUrl(that.data.activityId, pricePstCode)
                    // that.setData({
                    //   thisAddress: res.data.data.city
                    // })
                  }
                })
              }
            })
          } else {
            callback({
              'showSetting': true,
              'getSetting': true
            })
          }
        }
      })
    },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    setTimeout(()=>{
      this.setData({
        partnerInfo:getApp().globalData.partnerInfo
      })
      },500)
    // this.setData({
    //   videoData: [],
    //   leftList: [],
    //   rightList: [],
    // })
    // this.getVideoData(this.data.typeId)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})